package com.lagou.handler;

import com.lagou.boot.ServerBoot;
import com.lagou.service.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) msg;
            Class<?> serviceIntf = Class.forName(request.getServiceId());
            Object service = ServerBoot.beanMap.get(serviceIntf);
            Method invokedMethod = serviceIntf.getDeclaredMethod(request.getMethodId(), request.getParameterTypes());
            Object result = invokedMethod.invoke(service, request.getParameters());
            ctx.writeAndFlush(result);
        }
    }
}
